package vip.xumy.picture.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import vip.xumy.core.exception.CoreException;
import vip.xumy.core.utils.ImageType;
import vip.xumy.picture.mapper.PictureMapper;
import vip.xumy.picture.pojo.Picture;

/**
 * Do not use for any commercial purposes without permission
 * 
 * @author: mengyxu
 * @date: 2021年12月31日
 */

@Service
public class PictureService {
	@Autowired
	private PictureMapper pictureMapper;

	@Value("${picture.root.path}")
	public void setRootPath(String path) {
		if (path != null && path.endsWith("/")) {
			this.rootPath = path;
		} else {
			this.rootPath = path + "/";
		}
	}

	private String rootPath;

	public List<Picture> list(Picture example) {
		return pictureMapper.list(example);
	}

	public Picture save(MultipartFile file, String user) throws CoreException {
		byte[] data;
		try {
			data = file.getBytes();
		} catch (IOException e) {
			throw new CoreException("图片上传失败");
		}
		ImageType type = ImageType.getImageType(data);
		if (type == null) {
			throw new CoreException("未知的图片类型");
		}
		String uuid = UUID.randomUUID().toString();
		String path = uuid.replace("-", "/") + "." + type.getType();
		writeToFile(path, data);
		Picture picture = new Picture();
		picture.setUser(user);
		picture.setId(uuid.replace("-", ""));
		picture.setPath(path);
		picture.setStatus("0");
		picture.setSpace(Math.ceil(data.length * 1.0 / 1024) + "KB");
		pictureMapper.save(picture);
		return picture;
	}

	private void writeToFile(String path, byte[] data) throws CoreException {
		File file = new File(rootPath + path);
		File parent = file.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
		try (FileOutputStream fos = new FileOutputStream(file)) {
			fos.write(data);
		} catch (IOException e) {
			e.printStackTrace();
			file.delete();
			deleteEmptyDir(parent);
			throw new CoreException("图片保存失败");
		}
	}

	public void update(MultipartFile file, Picture picture) throws CoreException {
		if(file != null) {
			byte[] data;
			try {
				data = file.getBytes();
				writeToFile(picture.getPath(), data);
			} catch (IOException e) {
				throw new CoreException("图片上传失败");
			}
		}
		pictureMapper.update(picture);
	}

	public void delete(Picture picture) {
		deleteFile(picture.getPath());
		pictureMapper.delete(picture.getId());
	}

	private void deleteFile(String path) {
		File file = new File(rootPath + path);
		file.deleteOnExit();
		deleteEmptyDir(file.getParentFile());
	}

	private void deleteEmptyDir(File dir) {
		if (!dir.exists() || !dir.isDirectory()) {
			return;
		}
		if (dir.list().length == 0) {
			dir.delete();
			deleteEmptyDir(dir.getParentFile());
		}
	}

	public void deleteAll(String user) {
		pictureMapper.deleteAll(user);
	}

}
